Algorithm Implementation/Sorting/Selection sort

From Wikibooks, open books for an open world

This article describes implementations of the selection sort algorithm in a variety of real-world programming languages.

BASIC

FOR i = 1 TO length - 1
   min = i
   FOR j = i + 1 TO length
      IF data(min) > data(j) THEN
         min = j
      END IF
   NEXT j
   temp = data(i)
   data(i) = data(min)
   data(min) = temp
NEXT i

C

int selectionSort(int data[], int length)
{
    int i, j;
    int temp;
    int min;
    for (i = 0; i < length - 1; i++)
    {
        min = i; /* current minimum */
 
        /* find the global minimum */
        for (j = i + 1; j < length; j++)
            if (data[min] > data[j])
                min = j; /* new minimum */
 
        /* swap data[i] and data[minimum] */
        temp = data[i];
        data[i] = data[min];
        data[min] = temp;
    }
    return 0;
}

C#

public void sortArray(int[] data)
{
    int min, temp;
 
    for (int i = 0; i < data.Length - 1; i++)
    {
        min = i;
        for (int j = i + 1; j < data.Length; j++)
            if (data[j] < data[min])
                min = j;
 
        // swap the values
        temp = data[i];
        data[i] = data[min];
        data[min] = temp;
    }
}

Java

public static int[] selectionsort(int[] data)
{
    for (int i = 0; i < data.length - 1; i++)
    {
        int min = i;
        for (int j = i + 1; j < data.length; j++)
            if (data[j] < data[min]) //Finds smallest number
                min = j;
 
        int temp = data[min];  //Swap
        data[min] = data[i];
        data[i] = temp;
 
    }
    return data;
}

JavaScript

function selectionSort (data)
{
    var i, j, min, temp;
    for (i = 0; i < data.length - 1; i++)
    {
        min = i;
        for (j = i + 1; j < data.length; j++)
            if (data[j] < data[min])
                min = j;
 
        temp = data[min];
        data[min] = data[i];
        data[i] = temp;
    }
}

PHP

function selectionSort(&$d)
{
    $l = count($d);
    for ($i = 0; $i < $l - 1; $i++)
    {
        $min = $i;
        for ($j = $i + 1; $j < $l; $j++)
            if ($d[$j] < $d[$min])
                $min = $j;
 
        list($d[$i], $d[$min]) = array($d[$min], $d[$i]);
    }
}

Python

def selectionSort(data):
    length = len(data)
    for i in range(length - 1):
        min = i
        for j in range(i + 1, length):
            if data[j] < data[min]:
                min = j
        if min != i:
            data[i], data[min] = data[min], data[i]

Ruby

  def sort!(data)
    for i in 0..data.size-2
      min = i
      for j in i+1..data.size-1
        min = j if data[j] < data[min]
        end
      data[i], data[min] = data[min], data[i]
      end
    keys
  end